package com.tuuzed.android.sqlite;

import android.content.Context;
import android.support.annotation.NonNull;

import com.tuuzed.android.sqlite.args.DatabaseArgs;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public final class SQLiteManager {
    private static Map<Class<?>, SQLite> mDatabases = new ConcurrentHashMap<>();
    private static Class<?> defaultDatabaseClass;

    public static void initDatabase(@NonNull Context context, @NonNull Class<?> databaseClass) {
        initDatabase(context, DatabaseArgs.of(databaseClass));
    }

    public static void initDatabase(@NonNull Context context, @NonNull DatabaseArgs databaseArgs) {
        Context applicationContext = context.getApplicationContext();
        SQLite db = new SQLiteImpl().initialize(applicationContext, databaseArgs);
        mDatabases.put(databaseArgs.databaseClass, db);
        if (databaseArgs.defaultDatabase) {
            defaultDatabaseClass = databaseArgs.databaseClass;
        }
    }

    public static void destroy() {
        Collection<SQLite> values = mDatabases.values();
        for (SQLite it : values) {
            it.destroy();
        }
        mDatabases.clear();
    }

    @NonNull
    public static SQLite getSQLite() {
        if (defaultDatabaseClass == null) {
            throw new RuntimeException("not init default database");
        }
        return getSQLite(defaultDatabaseClass);
    }

    @NonNull
    public static SQLite getSQLite(Class<?> databaseClass) {
        SQLite andOrm = mDatabases.get(databaseClass);
        if (andOrm == null) {
            throw new RuntimeException("not init database: " + databaseClass.getName());
        }
        return andOrm;
    }
}
